﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace MyWcfRestLib.Files
{
    class CopyFileOperator : FileOperator
    {
        public CopyFileOperator(TwoPathOpParams theParams)
            : base(theParams)
        {
            FromFullPath = Path.Combine(DeviceRootFullPath, theParams.FromPath);
            ToFullPath = Path.Combine(DeviceRootFullPath, theParams.ToPath);
        }

        public string FromFullPath { get; private set; }

        public string ToFullPath { get; private set; }

        public bool IsSourceExist { get { return UtilityFunctions.PathExists(FromFullPath); } }

        public bool IsTargetExist { get { return UtilityFunctions.PathExists(ToFullPath); } }

        public bool IsDir
        {
            get { return Directory.Exists(FromFullPath); }
        }

        override public bool CanPerform
        {
            get
            {
                if (0 == string.Compare(FromFullPath, ToFullPath, true))
                    return false;

                bool yesICan = IsSourceExist && (!IsTargetExist);

                return yesICan;
            }
        }

        override public bool PerformOperation()
        {
            if (IsDir)
            {
                // TODO: Copy to temp folder, if completed then move to real target
                return CopyFolder(FromFullPath, ToFullPath);
            }
            else
            {
                return CopyFile(FromFullPath, ToFullPath);
            }

        }

        public static bool CopyFile(string fromPath, string toPath)
        {
            FileInfo file = new FileInfo(fromPath);
            try
            {
                file.CopyTo(toPath, false);
            }
            catch (IOException)
            {
                return false;
            }
            return true;
        }

        private bool CopyFolder(string fromPath, string toPath)
        {
            DirectoryInfo sourceFolder = new DirectoryInfo(fromPath);

            DirectoryInfo targetFolder = Directory.CreateDirectory(toPath);
            string targetPath = targetFolder.FullName;

            DirectoryInfo[] folders = sourceFolder.GetDirectories();
            foreach (var folder in folders)
            {
                CopyFolder(folder.FullName, Path.Combine(targetPath, folder.Name));
            }

            FileInfo[] files = sourceFolder.GetFiles();
            foreach (var file in files)
            {
                CopyFile(file.FullName, Path.Combine(targetPath, file.Name));
            }

            return true;

        }
    }
}
